/* tiffany_moments的数据结构(PostgreSQL)
CREATE TABLE tiffany_moments (
 id SERIAL PRIMARY KEY,
 nickname TEXT,
 content TEXT,
 images TEXT[],
 approved BOOLEAN DEFAULT FALSE,
 created_at TIMESTAMP DEFAULT NOW()
);
*/
const Router = require("@koa/router");
const { Pool } = require("pg");
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
const router = new Router({ prefix: "/moment" });

// 配置数据库连接池
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_DATABASE,
  password: process.env.DB_PASSWORD,
  port: process.env.DB_PORT,
});

// 频率限制存储 - 使用内存存储，生产环境建议使用Redis
const rateLimitStore = new Map();

// 频率限制中间件 - 限制每个IP每分钟最多3次请求
const rateLimitMiddleware = async (ctx, next) => {
  const clientIP = ctx.request.ip || ctx.request.ips[0] || 'unknown';
  const now = Date.now();
  const windowMs = 60 * 1000; // 1分钟
  const maxRequests = 3; // 最大请求次数
  
  // 清理过期的记录
  for (const [ip, data] of rateLimitStore.entries()) {
    if (now - data.timestamp > windowMs) {
      rateLimitStore.delete(ip);
    }
  }
  
  const clientData = rateLimitStore.get(clientIP);
  
  if (!clientData) {
    // 第一次请求
    rateLimitStore.set(clientIP, {
      count: 1,
      timestamp: now
    });
    return next();
  }
  
  if (now - clientData.timestamp > windowMs) {
    // 时间窗口已过，重置计数
    rateLimitStore.set(clientIP, {
      count: 1,
      timestamp: now
    });
    return next();
  }
  
  if (clientData.count >= maxRequests) {
    // 超过限制
    ctx.status = 429;
    ctx.body = {
      success: false,
      message: '请求过于频繁，请稍后再试'
    };
    return;
  }
  
  // 增加计数
  clientData.count++;
  rateLimitStore.set(clientIP, clientData);
  
  return next();
};

// 新增时刻接口
router.post("/", rateLimitMiddleware, async (ctx) => {
  try {
    const { nickname, content, images } = ctx.request.body;
    
    // 验证必填字段
    if (!content) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '内容字段是必填的'
      };
      return;
    }
    
    // 验证图片字段必填
    if (!images) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: 'images字段是必填的'
      };
      return;
    }
    
    // 验证图片数组格式
    if (!Array.isArray(images)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: 'images字段必须是数组格式'
      };
      return;
    }
    
    // 验证图片数组不能为空
    if (images.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: 'images数组不能为空'
      };
      return;
    }
    
    // 验证内容长度
    if (content.length > 1000) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '内容长度不能超过1000个字符'
      };
      return;
    }
    
    // 插入数据库
    const query = `
      INSERT INTO tiffany_moments (nickname, content, images)
      VALUES ($1, $2, $3)
      RETURNING id, created_at
    `;
    
    const values = [nickname || null, content, images];
    const result = await pool.query(query, values);
    
    ctx.status = 201;
    ctx.body = {
      success: true,
      message: '时刻提交成功',
      data: {
        id: result.rows[0].id,
        created_at: result.rows[0].created_at
      }
    };
    
  } catch (error) {
    console.error('新增时刻错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '服务器内部错误'
    };
  }
});

// 获取时刻列表接口 - 支持分页
router.get("/", async (ctx) => {
  try {
    // 获取分页参数，设置默认值
    const page = parseInt(ctx.query.page) || 1;
    const pageSize = parseInt(ctx.query.pageSize) || 10;
    
    // 验证分页参数
    if (page < 1 || pageSize < 1 || pageSize > 100) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '分页参数无效。页码必须大于0，每页数量必须在1-100之间'
      };
      return;
    }
    
    const offset = (page - 1) * pageSize;
    
    // 查询总记录数
    const countQuery = `
      SELECT COUNT(*) as total
      FROM tiffany_moments
      WHERE approved = TRUE
    `;
    
    // 查询分页数据
    const dataQuery = `
      SELECT id, nickname, content, images, created_at
      FROM tiffany_moments
      WHERE approved = TRUE
      ORDER BY created_at DESC
      LIMIT $1 OFFSET $2
    `;
    
    // 并行执行查询
    const [countResult, dataResult] = await Promise.all([
      pool.query(countQuery),
      pool.query(dataQuery, [pageSize, offset])
    ]);
    
    const total = parseInt(countResult.rows[0].total);
    const totalPages = Math.ceil(total / pageSize);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: {
        items: dataResult.rows,
        pagination: {
          page,
          pageSize,
          total,
          totalPages,
          hasNext: page < totalPages,
          hasPrev: page > 1
        }
      }
    };
    
  } catch (error) {
    console.error('获取时刻列表错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '服务器内部错误'
    };
  }
});

// 导出路由
module.exports = router;